import React from 'react';
import {Form, Button, Spin, Divider, Card, Row, Col, Tabs, message, Modal, Alert} from 'antd';
import update from 'lodash/update';
import cloneDeep from 'lodash/cloneDeep';
import get from 'lodash/get';
import TextInput from 'Shared/components/TextInput';
import Return from '../../common/Return';
import AddDetail from './AddDetail';
import AddVehicle from './AddVehicle';
import DetailSelectPanel from './DetailSelectPanel';
import styles from '../style.css';
import {formatMessage} from '../intl';
import {validateAdd} from './validate';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../../constants';
import WrappedDatePicker from '../../common/WrappedDatePicker';
import {getWarrantyPolicyDetail, updateWarrantyPolicy, addWarrantyPolicy} from '../api';
import routes from '../routes';
import {PERMISSIONS} from '../constants';
import {conventEnumValueToString, uuid} from '../../utils';
import {isHavePermission} from '../utils';
import {warrantyPolicyType, dealerType} from '../../Enum';
import DealerSelectPanel from '../../common/DealerSelect/SelectEdit';
import {PermissionsContext, InitDataContext} from '../contexts';

import WrappedSelect from '../../common/WrappedSelect';
export const dealerConditions = {
    type: dealerType.总代
};
const FormItem = Form.Item;
const autosize = {minRows: 1};
const TabPane = Tabs.TabPane;

export default class AddPage extends React.PureComponent {
    state = {
        data: {
            items: [],
        },

        loading: false,
        hasOperat: false,
        isValidate: false,
        isFetchFee: false,
        showPanel: false,
        closable: false
    };

    componentDidMount() {
        if(this.props.id) {
            this.setState({
                loading: true
            });
            getWarrantyPolicyDetail(this.props.id).then(res => {
                if(res.ok)
                    this.setState({
                        data: res.data,
                        loading: false
                    });
                else
                    this.setState({
                        loading: false
                    });
            });
        }
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
    }
    
    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    }

    goBack = () => {
        this.props.history.push({
            pathname: routes.query.url(),
            state: {query: true}
        });
    }

    generateTabName = items => {
        const indexObj = {};
        for(let i = 0; i < items.length; i++) {
            const item = items[i];
            const type = item.warrantyPolicyType;
            if(!type) {
                item.tabName = formatMessage({
                    id: 'add.type.add',
                    defaultMessage: '新增'
                });
                continue;
            }

            if(indexObj[type])
                indexObj[type] += 1;
            else
                indexObj[type] = 1;
            item.tabName = `${conventEnumValueToString(warrantyPolicyType, type)}${indexObj[type]}`;
        }
        return items;
    }

    onChange = (value, name) => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: update(newData, name, () => value)
            };
        });
    };

    onSelectDealer = (condition = {}) => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: {
                    ...newData,
                    dealerId: condition.id,
                    dealerCode: condition.code,
                    dealerName: condition.name,
                    country: condition.countryName
                }
            };
        });
    };
    onConcat = (arrayPath, data, selectPath) => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: update(newData, arrayPath, array => {
                    array = array || [];
                    // const insert = [];
                    // const select = get(newData, selectPath);
                    // if(select) {
                    //     if(select.warrantyPolicyType === warrantyPolicyType.标准)
                    //         data.forEach(r => {
                    //             console.log(1);
                    //             const newDataArray = newData.filter(v => v.warrantyPolicyType === select.warrantyPolicyType);
                    //             // newData.map(o => {
                    //             //     const index = o.vehicles.findIndex(v => v.productCategoryId === r.productCategoryId);
                    //             //     if(index === -1)
                    //             //         insert.push(r);
                    //             // });
                    //         });
                    //     if(select.warrantyPolicyType === warrantyPolicyType.特殊)
                    //         data.forEach(r => {
                    //             const newDataArray = newData.filter(v => v.warrantyPolicyType === select.warrantyPolicyType);
                    //             newDataArray.forEach(o => {
                    //                 const index = o.vehicles.findIndex(v => v.vehicleId === r.vehicleId);
                    //                 if(index === -1)
                    //                     insert.push(r);
                    //             });
                    //         });
                    //     return array.concat(insert);
                    // }
                    return array.concat(data);
                })
            };
        });
    }

    onRemove = (arrayPath, index) => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: update(newData, arrayPath, array => array.filter((v, i) => String(i) !== String(index)))
            };
        });
    }

    onRemoveAll = arrayPath => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: update(newData, arrayPath, () => [])
            };
        });
    }

    onSubmit = () => {
        const result = validateAdd(this.state.data, this.props.id);
        if(result) {
            this.setState({
                isValidate: true,
                detailId: result.detailId
            });
            return message.warn(result.message);
        }
        this.setState({
            loading: true
        });
        const data = this.state.data;
        const commonData = {
            name: data.name,
            startTime: data.startTime,
            remark: data.remark,
            items: data.items.map(item => {
                const result = {
                    warrantyPolicyType: item.warrantyPolicyType,
                    warrantyMileage: item.warrantyMileage,
                    warrantyMonth: item.warrantyMonth,
                    saleStartDate: item.saleStartDate,
                    saleEndDate: item.saleEndDate,
                };
                const materialsMap = m => ({
                    partWarrantyCategoryId: m.partWarrantyCategoryId,
                    warrantyDuration: m.warrantyDuration,
                    warrantyMileage: m.warrantyMileage,
                    remark: m.remark
                });
                const {vehicles = []} = item;
                if(item.warrantyPolicyType === warrantyPolicyType.标准)
                    result.productCategories = vehicles.map(v => ({
                        productCategoryId: v.productCategoryId,
                        vehicleProperty: v.vehicleProperty,
                        vehicleClaimType: v.vehicleClaimType,
                        materials: (v.materials || []).map(materialsMap)
                    }));
                if(item.warrantyPolicyType === warrantyPolicyType.特殊)
                    result.vehicles = vehicles.map(v => ({
                        vehicleId: v.vehicleId,
                        materials: (v.materials || []).map(materialsMap)
                    }));
                return result;
            })
        };

        if(this.props.id) {
            commonData.rowVersion = data.rowVersion;
            // 编辑
            updateWarrantyPolicy(this.props.id, commonData).then(res => {
                if(res.ok)
                    this.goBack();
                else
                    this.setState({
                        loading: false
                    });
            });
        } else {
            commonData.code = data.code;
            commonData.dealerId = data.dealerId;
            commonData.brandId = data.brandId;
            addWarrantyPolicy(commonData).then(res => {
                if(res.ok)
                    this.goBack();
                else
                    this.setState({
                        loading: false
                    });
            });
        }
    };

    onChangeTabs = id => {
        this.setState({detailId: id});
    }

    onDeleteTab = targetKey => {
        const items = this.state.data.items;
        const index = items.findIndex(item => item.id === targetKey);
        this.onRemove('items', index);
        if(items.length)
            this.setState({detailId: items[0].id});
    }
    onSelect = record => {
        if(!record) return;
        this.onConcat('items', [record]);
        this.setState({
            showPanel: false,
            detailId: record.id
        });
    }

    onClickDeleteDetail = () => {
        this.setState({
            closable: !this.state.closable
        });
    }

    onClickAddDetail = () => {
        const {data} = this.state;
        if(!data.dealerId)
            return message.warn(formatMessage({
                id: 'add.onClickAddDetail.message',
                defaultMessage: '请先选择总代'
            }));
        const id = uuid();
        this.onConcat('items', [{id}]);
        this.setState({detailId: id});
    }

    render() {
        const {data} = this.state;
        const items = this.generateTabName(data.items);
        const tabs = items.map((item, index) => <TabPane
            closable={this.state.closable} tab={item.tabName} key={item.id}>
            <AddDetail
                name={`items[${index}]`}
                isValidate={this.state.isValidate}
                onChange={this.onChange}
                onRemoveAll={this.onRemoveAll}
                data={item} />
            {item.warrantyPolicyType ? <React.Fragment>
                <Divider />
                <AddVehicle
                    name={`items[${index}]`}
                    isValidate={this.state.isValidate}
                    onSelect={this.onConcat}
                    onChange={this.onChange}
                    onRemove={this.onRemove}
                    onRemoveAll={this.onRemoveAll}
                    data={item}
                    dealerId={data.dealerId} />
            </React.Fragment> : null}
        </TabPane>);
        const defaultTabKey = items.length ? items[0].id : '';
        const alertMessage = (
            <Row>
                <Col span={18}>{formatMessage({
                    id: 'add.alert.message',
                    defaultMessage: '点击标签页右侧图标可删除该条款，删除后无法撤销'
                })}</Col>
                <Col span={6} className="col-align-right">
                    <a onClick={this.onClickDeleteDetail}>{formatMessage({
                        id: 'add.btn.return',
                        defaultMessage: '退出'
                    })}</a>
                </Col>
            </Row>);
        return (
            <div className={styles.detail}>
                <Modal
                    title={formatMessage({
                        id: 'add.detail.modal.title',
                        defaultMessage: '整车索赔条款查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showPanel}
                    onCancel={this.showPanel}>
                    <DetailSelectPanel onSelect={this.onSelect} />
                </Modal>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            title={formatMessage({
                                id: 'add.order.title',
                                defaultMessage: '政策信息'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'queryPanel.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.isValidate && !data.dealerId ? 'error' : null}
                                        required>
                                        {this.props.id
                                            ? <span className="value-font">{`(${data.dealerCode})${data.dealerName}`}</span>
                                            : <DealerSelectPanel
                                                allowClear={false}
                                                value={data.dealerId ? {
                                                    id: data.dealerId,
                                                    code: data.dealerCode,
                                                    name: data.dealerName
                                                } : null}
                                                conditions={dealerConditions}
                                                onSelect={this.onSelectDealer} />}
                                    </FormItem>
                                </Col>

                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'queryPage.brandId',
                                        defaultMessage: '品牌'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={this.state.isValidate && !data.brandId ? 'error' : null}
                                    required>
                                        {this.props.id
                                            ? <span className="value-font">{`(${data.brandCode})${data.brandName}`}</span>
                                            : <InitDataContext.Consumer>
                                                {
                                                    brands => (
                                                        <WrappedSelect
                                                            name="brandId"
                                                            allowClear
                                                            options={brands}
                                                            value={data.brandId}
                                                            onChange={this.onChange} />
                                                    )
                                                }
                                            </InitDataContext.Consumer>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'add.form.code',
                                        defaultMessage: '编号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={this.state.isValidate && !data.code ? 'error' : null}
                                    required>
                                        {this.props.id
                                            ? <span className="value-font">{data.code}</span>
                                            : <TextInput
                                                name="code"
                                                value={data.code}
                                                onBlur={this.onChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'add.form.name',
                                        defaultMessage: '名称'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={this.state.isValidate && !data.name ? 'error' : null}
                                    required>
                                        <TextInput
                                            name="name"
                                            value={data.name}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'add.form.startTime',
                                            defaultMessage: '启用日期'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.isValidate && !data.startTime ? 'error' : null}
                                        required>
                                        <WrappedDatePicker
                                            name="startTime"
                                            value={data.startTime}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'add.form.country',
                                            defaultMessage: '国家'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem
                                    label={formatMessage({
                                        id: 'add.form.remark',
                                        defaultMessage: '备注'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TextInput type="textarea" name="remark" autosize={autosize}
                                        value={data.remark} onBlur={this.onChange} />
                                </FormItem>
                            </Row>
                        </Card>
                        <Card
                            extra={<React.Fragment>
                                <Button size="small" onClick={this.onClickAddDetail}>{formatMessage({
                                    id: 'add.detail.btn.add',
                                    defaultMessage: '新增'
                                })}</Button>
                                <Button size="small" onClick={this.showPanel}>{formatMessage({
                                    id: 'add.detail.btn.copy',
                                    defaultMessage: '复制'
                                })}</Button>
                                <Button size="small" disabled={this.state.closable || !items.length}
                                    onClick={this.onClickDeleteDetail}>{formatMessage({
                                        id: 'add.detail.btn.delete',
                                        defaultMessage: '删除'
                                    })}</Button>
                            </React.Fragment>}
                            title={formatMessage({
                                id: 'add.detail.title',
                                defaultMessage: '条款信息'
                            })}>
                            {this.state.closable && <Alert className={styles.alertMargin} type="warning" message={alertMessage} showIcon />}
                            <Tabs
                                hideAdd type="editable-card"
                                activeKey={this.state.detailId || defaultTabKey}
                                onChange={this.onChangeTabs} onEdit={this.onDeleteTab}>
                                {tabs}
                            </Tabs>
                        </Card>
                        <PermissionsContext.Consumer>
                            {pagePermissions => (
                                (
                                    this.props.id
                                        ? isHavePermission(PERMISSIONS.update, pagePermissions, data.options)
                                        : isHavePermission(PERMISSIONS.add, pagePermissions)
                                ) &&
                                <Card type="inner" className={styles.noMarginTop}>
                                    <Row>
                                        <Col className="col-align-right">
                                            <Button
                                                key="audit"
                                                loading={this.state.loading}
                                                onClick={this.onSubmit}
                                                type="primary">
                                                {formatMessage({
                                                    id: 'add.btn.submit',
                                                    defaultMessage: '保存'
                                                })}
                                            </Button>
                                        </Col>
                                    </Row>
                                </Card>
                            )}
                        </PermissionsContext.Consumer>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.goBack} />
                </div>
            </div>
        );
    }
}
